<?php
// +----------------------------------------------------------------------
// | @projectName  【order_system---点餐系统】
// +----------------------------------------------------------------------
// | @author        山西创客空间科技有限公司
// +----------------------------------------------------------------------
// | @date          2017年10月13日 星期五
// +----------------------------------------------------------------------
// | @Copyright     http://sx-ck.com All rights reserved.      
// +----------------------------------------------------------------------
namespace app\admin\controller;
use app\admin\model\Common;
use app\common\Base;
use app\common\Error;
use think\Controller;
use think\Db;
use think\Request;

class DishSales extends Base 
{
    public function index () {
        return $this -> fetch ();
    }
    // 根据条件组织查询查询数据的岂止时间
    private function handle_start_end ($times) 
    {
        switch ($times) {
            // 当值为0的时候，按当天数据查询
            case '0':
                $start = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d"),date("Y")));
                $end = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d"),date("Y")));
                break;
            // 当值为1的时候，按周查询    
            case '1':
                $start = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));
                $end = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));
                break;
            // 当值为2的时候，按月查询    
            case '2':
                $start = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y")));
                $end = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y")));  
                break;
            // 当值为3的时候，按季度查询
            case '3':
                //当月是第几季度              
                $season = ceil((date('n'))/3);
                $start = date('Y-m-d H:i:s', mktime(0, 0, 0,$season*3-3+1,1,date('Y')));
                $end = date('Y-m-d H:i:s', mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y')));  
                break;
            // 当值为4的时候，按年查询
            case '4':
                $start = date('Y-01-01 00:00:00');  
                $end = date('Y-12-31 23:59:59'); 
                break;
            default:
                $start = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d"),date("Y")));
                $end = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d"),date("Y")));
                break;
        }
        $result = array('order_time' => array( '$gt' => $start, '$lt' => $end ));
        return $result;
    }
    // 查询处理数据
    private function handle_data ($query) 
    {
        // 连接mongodb数据库
        $dbname = 'order_system_'.date('Y');
        $db = Base::connect_mongodb($dbname);
        $row = [];        //用来接收最终数据的返回结果
        // 查询所有窗口
        $window = Db::name('window');
        $windowRow = $window -> field('id') -> select();
        if ($windowRow === false) {
            return Base::echo_error(Error::DB_ERROR);
        }
        // 创建数组用来接收单个菜的数据
        $cook_row = [];        
        foreach ($windowRow as $windowkey => $windowVal) {
            // 连接表
            $collection = $db -> selectCollection(md5($windowVal['id']));
            $cursor = $collection -> find($query);
            if ($cursor === false) {
                return Base::echo_error(Error::DB_ERROR);
            }
            foreach ($cursor as $doc) {
                foreach ($doc['order_info'] as $key => $docVal) {
                    $cook_row[] = $docVal;
                }
            }
        }
        // 当接收所有菜的数据为空的时候直接返回不需要处理
        if (count($cook_row) == 0) {
            return $row; 
        }
        // 查询所有菜品
        $cook_menu = Db::name('cook_menu');
        $cook_menu_arr = $cook_menu  -> field('id') -> select();
        if ($cook_menu_arr === false) {
            return Base::echo_error(Error::DB_ERROR);
        }

        // 用来接收整理所需要的数据格式********以菜品为单位进行数据处理
        // 格式为 [['cook_menu_id'=>'',....],[]...]
        foreach ($cook_menu_arr as $idkey => $idVal) {
            $num = 0;               //记录每个菜的销售总数量
            $total_price = 0;       //记录单个菜的总价
            foreach ($cook_row as $key => $value) {
                if ($value['cook_menu_id'] == $idVal['id']) {
                    // 满足条件进行累加的运算
                    $num += $value['num'];
                    $total_price += $value['total_price'];
                    $row[$idkey] = [
                        'cook_menu_id' => $value['cook_menu_id'],
                        'cook_menu_name' => $value['cook_menu_name'],
                        'num' => $num,
                        'total_price' => $total_price
                    ];
                }
            }
        }
        return $row;
    }
    // 查询菜品销量统计排序
    public function dish_sales_data () 
    {
        // 验证参数的合法性
        $times = $this -> request -> post('times');
        if (Common::check_empty($times) === true) {
            return Base::echo_error(Error::MEALS_TIME_ID_IS_EMPTY);
        }
        
        $sort_rule = $this -> request -> post('sort_rule');
        if (Common::check_empty($sort_rule) === true) {
            return Base::echo_error(Error::SORT_RULE_IS_EMPTY);
        }

        // 调用查询条件的接口处理查询条件
        $query = $this -> handle_start_end($times);
        $row = $this -> handle_data($query);
        switch ($sort_rule) {
            case '0':
                $row = $this -> f_order_sort($row,'num',2);
                break;
            case '1':
                $row = $this -> f_order_sort($row,'num',1);
                break;
            case '2':
                $row = $this -> f_order_sort($row,'total_price',2);
                break;
            case '3':
                $row = $this -> f_order_sort($row,'total_price',1);
                break;
            default:
                $row = $this -> f_order_sort($row,'num',2);
                break;
        }    
        return Base::echo_success($row);
    }

    

}